<template>
  <q-tab-panels v-model="tab">
    <q-tab-panel name="viewUser" class="full-width">
      <q-toolbar class="shadow-2">
        <q-btn flat round dense icon="menu" class="q-mr-sm" />
        <q-toolbar-title>用户总览</q-toolbar-title>
        <q-input v-model="searchText" dense class="q-ml-md col-8">
          <template #append>
            <q-icon name="search" />
            <q-icon
              v-if="searchText !== ''"
              name="clear"
              class="cursor-pointer"
              @click="text = ''"
            />
          </template>
        </q-input>
      </q-toolbar>
      <q-banner>仅支持修改用户权限！</q-banner>
      <q-table
        v-model:pagination="userPagination"
        :loading="loading"
        :columns="columns"
        :rows="data"
        :filter="searchText"
        row-key="id"
        @request="requestUserPage"
      >
        <template #body="prop">
          <q-tr :props="prop">
            <q-td>
              <q-btn @click="deleteUser(prop.row.id)">
                <q-icon name="delete"></q-icon>
              </q-btn>
              <q-btn @click="editUser(prop.row.id, prop.row.role)">
                <q-icon name="edit"></q-icon>
              </q-btn>
            </q-td>
            <q-td
              v-for="(item, index) in prop.row"
              :key="index"
              style="
                max-width: 500px;
                width: fit-content;
                text-overflow: ellipsis;
                overflow: hidden;
              "
            >
              <q-input
                v-if="index == 'role'"
                v-model="prop.row[index]"
                input-style="text-align:center"
              ></q-input>
              <p v-else>
                {{ item }}
                <q-tooltip style="overflow: visible">{{ item }}</q-tooltip>
              </p>
            </q-td>
          </q-tr>
        </template>
      </q-table>
    </q-tab-panel>

    <q-tab-panel name="statUser" class="flex-center">
      <q-card class="row flex-center full-width justify-around">
        <q-date
          v-model="date"
          title="选择统计日期"
          subtitle="可选择范围"
          range
          @range-end="dateselected"
        ></q-date>
        <div v-if="date" class="row items-center">
          <q-card v-if="date.hasOwnProperty('from')">
            <div
              id="mychart"
              ref="chartref"
              style="width: 100vh; height: 80vh"
            ></div>
          </q-card>
          <q-card v-else-if="date == null"></q-card>
          <q-card v-else style="height: fit-content">
            <q-card-section>
              <div class="text-h6">{{ date }}当日的独立访问量</div>
            </q-card-section>
            <q-card-section>
              <div class="text-center" style="font-size: xx-large">
                {{ singleuv }}
              </div>
            </q-card-section>
          </q-card>
        </div>
      </q-card>
    </q-tab-panel>
  </q-tab-panels>
</template>
<script setup>
import { computed, nextTick, onMounted, onUpdated, ref } from "vue";
import { baseurl } from "src/js/global";
import { get, post } from "src/js/fetch";
import { useQuasar } from "quasar";
import { option } from "src/js/uvDataEchart";
import * as echarts from "echarts";
import dayjs from "dayjs";
import "dayjs/locale/zh-cn";

onMounted(() => {
  getUsers(1, 5);
});
const date = ref(null);
const loading = ref(false);
const data = ref([]);
const $q = useQuasar();
const userPagination = ref({
  sortBy: null,
  page: 1,
  rowsPerPage: 5,
  rowsNumber: 0,
});

const singleuv = ref(0);
function dateselected() {
  if (date.value.hasOwnProperty("from")) {
    multipleDaySelected();
  } else {
    singleDaySelected();
  }
}
function singleDaySelected() {
  const url = new URL(baseurl + "user/uv");
  url.searchParams.set("date", date.value);
  get(url).then((res) => {
    singleuv.value = res.data;
  });
}
function multipleDaySelected() {
  const day1 = dayjs(date.value.from);
  const day2 = dayjs(date.value.to);
  const ago = day2.diff(day1, "days");
  const url = new URL(baseurl + "user/uv");
  let datas = [];
  for (let i = 0; i <= ago; i++) {
    const tarday = day1.add(i, "d").format("YYYY-MM-DD");
    let temp = { date: tarday, UV: 0 };
    url.searchParams.set("date", tarday);
    get(url).then((res) => {
      console.log(tarday, res.data);
      temp.UV = res.data;
    });
    datas.push(temp);
  }

  console.log("datas", datas);
  option.dataset.source = datas;
  // nextTick(() => {
  setTimeout(initchart, 200);
  // });
}
function initchart() {
  const chartref = document.getElementById("mychart");
  console.log(option);
  const mychart = echarts.init(chartref);
  mychart.setOption(option);
}

function requestUserPage(props) {
  const { page, rowsPerPage, sortBy, descending } = props.pagination;
  console.log(page);
  getUsers(page, rowsPerPage);
  userPagination.value.page = page;
  userPagination.value.rowsPerPage = rowsPerPage;
}
function getUsers(current, size) {
  const url = new URL(baseurl + "user/list");
  url.searchParams.set("current", current);
  url.searchParams.set("size", size);
  loading.value = true;
  get(url).then((res) => {
    console.log(res.data);
    data.value = res.data;
    userPagination.value.rowsNumber = parseInt(res.totalPage) * 5;
  });
  loading.value = false;
}

function deleteUser(userid) {
  const url = new URL(baseurl + "user/delete");
  url.searchParams.set("userId", userid);
  post(url).then((res) => {
    if (res.success) {
      $q.notify({
        message: res.data,
        type: "positive",
        position: "center",
      });
      getUsers(userPagination.value.page, userPagination.value.rowsPerPage);
    } else {
      $q.notify({
        message: res.errorMsg,
        type: "negative",
        position: "center",
      });
    }
  });
}
function editUser(id, role) {
  console.log(id, role);
  const url = new URL(baseurl + "user/permission/set");
  url.searchParams.set("userId", id);
  url.searchParams.set("role", role);
  post(url).then((res) => {
    if (res.success) {
      $q.notify({
        message: res.data,
        type: "positive",
        position: "center",
      });
      getUsers(userPagination.value.page, userPagination.value.rowsPerPage);
    } else {
      $q.notify({
        message: res.errorMsg,
        type: "negative",
        position: "center",
      });
    }
  });
}

const searchText = ref("");
const columns = [
  {
    name: "action",
    label: "操作",
    align: "center",
  },
  {
    name: "userId",
    label: "用户ID",
    align: "center",
    field: "id",
    sortable: true,
  },
  {
    name: "username",
    label: "用户名",
    align: "center",
    field: "username",
    sortable: true,
  },
  {
    name: "password",
    label: "密码",
    align: "left",
    field: "password",
    sortable: false,
  },
  {
    name: "email",
    label: "电子邮箱",
    align: "center",
    field: "email",
    sortable: true,
  },
  {
    name: "role",
    label: "用户身份(stu/adm/tec)",
    align: "center",
    field: "role",
    sortable: true,
  },

  {
    name: "imgrUrl",
    label: "图片链接",
    align: "center",
    field: "imgUrl",
    sortable: true,
  },
];

const props = defineProps({ current: { type: String, default: "viewUser" } });
const tab = computed(() => {
  return props.current;
});
</script>
<style scoped></style>
